package com.zhisheng.springbootredis.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhisheng.springbootredis.entity.Product;
import com.zhisheng.springbootredis.mapper.ProductMapper;
import com.zhisheng.springbootredis.service.ProductService;
import com.zhisheng.springbootredis.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * (Product)表服务实现类
 *
 * @author 杨小龙
 * @since 2025-10-20 16:58:26
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询商品先从redis再从mysql
    public R<Product> selectById(Long id){
        //先从redis查询
        ValueOperations forValue = redisTemplate.opsForValue();
        Object o = forValue.get("P:" + id);
        Product product = null;
        if(o==null){
            //从数据库查询
            product = productMapper.selectById(id);
            if(product==null){
                //给redis存一个空对象  三分钟过期
                forValue.set("P:"+id,"", Duration.between(LocalDateTime.now(),LocalDateTime.now().plusMinutes(3)));
            }else {
                //数据库不为空那么就给redis添加数据  五分钟过期
                //将对象转成字符串存入:
                String string = JSONObject.toJSONString(product);
                forValue.set("P:"+id,string,5, TimeUnit.MINUTES);
            }

        }else {
            if(!"".equals(o)){
                //将json字符串转成对象
                 product= JSONObject.parseObject(o.toString(), Product.class);
            }
        }
        return R.success(product);
    }

}
